import { useState, useEffect } from 'react';
import { useLanguage } from '@kernelproxy/i18n';
import { Button } from '@kernelproxy/ui';
import { authService } from '../services/auth';
import { Shield, Key, AlertCircle } from 'lucide-react';

const MFASettings = () => {
  const [loading, setLoading] = useState(false);
  const [checkingStatus, setCheckingStatus] = useState(true);
  const [mfaEnabled, setMfaEnabled] = useState(false);
  const [qrCode, setQrCode] = useState('');
  const [secret, setSecret] = useState('');
  const [otp, setOtp] = useState('');
  const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [showSetup, setShowSetup] = useState(false);
  const { language } = useLanguage();

  useEffect(() => {
    checkMFAStatus();
  }, []);

  const checkMFAStatus = async () => {
    setCheckingStatus(true);
    try {
      const result = await authService.getMFAFactors();
      if (result.success && result.factors) {
        setMfaEnabled(result.factors.totp || false);
      }
    } catch (err) {
      console.error('Failed to check MFA status:', err);
    } finally {
      setCheckingStatus(false);
    }
  };

  const handleEnableMFA = async () => {
    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const result = await authService.createMFAAuthenticator();
      if (result.success && result.data) {
        setQrCode(result.data.uri);
        setSecret(result.data.secret);
        setShowSetup(true);
      } else {
        setError(language === 'zh-CN' ? '启用MFA失败' : 'Failed to enable MFA');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '启用MFA失败' : 'Failed to enable MFA');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOTP = async () => {
    if (!otp || otp.length !== 6) {
      setError(language === 'zh-CN' ? '请输入6位验证码' : 'Please enter 6-digit code');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const result = await authService.verifyMFAAuthenticator(otp);
      if (result.success) {
        // Generate recovery codes
        const codesResult = await authService.generateMFARecoveryCodes();
        if (codesResult.success && codesResult.recoveryCodes) {
          setRecoveryCodes(codesResult.recoveryCodes.recoveryCodes || []);
        }
        
        setSuccess(language === 'zh-CN' ? 'MFA已成功启用！' : 'MFA enabled successfully!');
        setMfaEnabled(true);
        setShowSetup(false);
      } else {
        setError(language === 'zh-CN' ? '验证码无效' : 'Invalid verification code');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '验证失败' : 'Verification failed');
    } finally {
      setLoading(false);
    }
  };

  const handleDisableMFA = async () => {
    if (!confirm(language === 'zh-CN' ? '确定要禁用双因素认证吗？' : 'Are you sure you want to disable two-factor authentication?')) {
      return;
    }

    setLoading(true);
    setError('');

    try {
      const result = await authService.updateMFAStatus(false);
      if (result.success) {
        setMfaEnabled(false);
        setSuccess(language === 'zh-CN' ? 'MFA已禁用' : 'MFA disabled');
      } else {
        setError(language === 'zh-CN' ? '禁用MFA失败' : 'Failed to disable MFA');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '禁用MFA失败' : 'Failed to disable MFA');
    } finally {
      setLoading(false);
    }
  };

  const downloadRecoveryCodes = () => {
    const blob = new Blob([recoveryCodes.join('\n')], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'mfa-recovery-codes.txt';
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="max-w-2xl mx-auto p-6">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
          <Shield className="w-8 h-8 text-[#00d4ff]" />
          {language === 'zh-CN' ? '双因素认证' : 'Two-Factor Authentication'}
        </h1>
        <p className="mt-2 text-gray-600 dark:text-gray-400">
          {language === 'zh-CN' 
            ? '为您的账户添加额外的安全层' 
            : 'Add an extra layer of security to your account'}
        </p>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
        </div>
      )}

      {success && (
        <div className="mb-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-md">
          <p className="text-sm text-green-600 dark:text-green-400">{success}</p>
        </div>
      )}

      {recoveryCodes.length > 0 && (
        <div className="mb-6 p-6 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md">
          <h3 className="text-lg font-semibold text-yellow-900 dark:text-yellow-200 mb-2 flex items-center gap-2">
            <Key className="w-5 h-5" />
            {language === 'zh-CN' ? '恢复代码' : 'Recovery Codes'}
          </h3>
          <p className="text-sm text-yellow-800 dark:text-yellow-300 mb-4">
            {language === 'zh-CN' 
              ? '请妥善保存这些恢复代码。如果您无法访问认证应用，可以使用这些代码登录。' 
              : 'Please save these recovery codes. You can use them to log in if you lose access to your authenticator app.'}
          </p>
          <div className="grid grid-cols-2 gap-2 mb-4 font-mono text-sm bg-white dark:bg-gray-800 p-4 rounded">
            {recoveryCodes.map((code, index) => (
              <div key={index} className="text-gray-900 dark:text-gray-100">{code}</div>
            ))}
          </div>
          <Button onClick={downloadRecoveryCodes} variant="outline" size="sm">
            {language === 'zh-CN' ? '下载恢复代码' : 'Download Recovery Codes'}
          </Button>
        </div>
      )}

      <div className="bg-white dark:bg-gray-800 p-6 rounded-lg shadow">
        {checkingStatus ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00d4ff]"></div>
            <span className="ml-3 text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' ? '加载中...' : 'Loading...'}
            </span>
          </div>
        ) : !showSetup && !mfaEnabled ? (
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              {language === 'zh-CN' ? '启用双因素认证' : 'Enable Two-Factor Authentication'}
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              {language === 'zh-CN' 
                ? '使用认证应用（如Google Authenticator、Authy）来保护您的账户。' 
                : 'Use an authenticator app (like Google Authenticator, Authy) to protect your account.'}
            </p>
            <Button onClick={handleEnableMFA} disabled={loading} variant="gradient">
              {loading 
                ? (language === 'zh-CN' ? '设置中...' : 'Setting up...') 
                : (language === 'zh-CN' ? '启用MFA' : 'Enable MFA')}
            </Button>
          </div>
        ) : showSetup ? (
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              {language === 'zh-CN' ? '设置认证应用' : 'Setup Authenticator App'}
            </h3>
            
            <div className="mb-6">
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                {language === 'zh-CN' 
                  ? '1. 在您的手机上打开认证应用，扫描下方二维码' 
                  : '1. Open your authenticator app and scan the QR code below'}
              </p>
              {qrCode && (
                <div className="flex justify-center mb-4 bg-white p-4 rounded">
                  <img src={qrCode} alt="QR Code" className="w-48 h-48" />
                </div>
              )}
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                {language === 'zh-CN' ? '或手动输入密钥：' : 'Or enter the key manually:'}
              </p>
              <code className="block bg-gray-100 dark:bg-gray-700 p-2 rounded text-sm font-mono text-gray-900 dark:text-gray-100 break-all">
                {secret}
              </code>
            </div>

            <div className="mb-6">
              <label htmlFor="otp" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {language === 'zh-CN' ? '2. 输入应用显示的6位验证码' : '2. Enter the 6-digit code from your app'}
              </label>
              <input
                id="otp"
                type="text"
                value={otp}
                onChange={e => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                maxLength={6}
                placeholder="000000"
                className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff]"
              />
            </div>

            <div className="flex gap-2">
              <Button onClick={handleVerifyOTP} disabled={loading || otp.length !== 6} variant="gradient">
                {loading 
                  ? (language === 'zh-CN' ? '验证中...' : 'Verifying...') 
                  : (language === 'zh-CN' ? '验证并启用' : 'Verify and Enable')}
              </Button>
              <Button onClick={() => setShowSetup(false)} variant="outline">
                {language === 'zh-CN' ? '取消' : 'Cancel'}
              </Button>
            </div>
          </div>
        ) : mfaEnabled && !showSetup ? (
          <div>
            <div className="flex items-center gap-2 mb-4">
              <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              <span className="text-green-600 dark:text-green-400 font-medium">
                {language === 'zh-CN' ? 'MFA已启用' : 'MFA Enabled'}
              </span>
            </div>
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              {language === 'zh-CN' 
                ? '您的账户已受到双因素认证保护。' 
                : 'Your account is protected with two-factor authentication.'}
            </p>
            <Button onClick={handleDisableMFA} disabled={loading} variant="outline">
              {loading 
                ? (language === 'zh-CN' ? '禁用中...' : 'Disabling...') 
                : (language === 'zh-CN' ? '禁用MFA' : 'Disable MFA')}
            </Button>
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default MFASettings;
